import React from "react";
import { connect, useDispatch } from "react-redux";
import actions from "@/store/actions/profile";
import { RouteComponentProps } from "react-router-dom";
import NavHeader from "@/components/Nav";
import { Form, Input, Button, message, useForm, Icon } from "bigbear-ui";
import { CustomCombinedState } from "@/store/reducers";
import { ProfileState } from "@/store/reducers/profile";
import { push } from "connected-react-router";

type Props = RouteComponentProps & ProfileState;

function Register(props: Props) {
	const dispatch = useDispatch();
	const [handleSubmit, callbackObj, validate, blurObj] = useForm([
		{
			name: "username",
			validate: [{ validate: (e) => e !== "", message: "用户名不能为空" }],
		},
		{
			name: "password",
			validate: [
				{ validate: (e) => e !== "", message: "密码不为空" },
				{
					validate: (e) => e.length > 2 && e.length < 7,
					message: "密码必须大于2位或者小于7位",
				},
			],
		},
	]);
	const onSubmit = (data: any) => {
		console.log(data);
		if (
			validate.username.length === 0 &&
			validate.password.length === 0 &&
			data &&
			data.username &&
			data.password
		) {
			dispatch(actions.login(data));
		} else {
			message.danger("验证失败", {});
		}
	};
	return (
		<>
			<NavHeader history={props.history}>用户登录</NavHeader>

			<Form className="login-form ">
				<div className="logo">BIGBEAR-UI</div>
				<Input
					prepend={<Icon icon="user"></Icon>}
					callback={(e) => callbackObj.username(e.target.value)}
					onBlur={(e: React.FocusEvent<HTMLInputElement>) => {
						blurObj.username(e.target.value);
					}}
					placeholder="用户名"
				></Input>
				<div className="bigbear-form-validate">
					{validate.username.map((v: string) => v)}
				</div>
				<Input
					prepend={<Icon icon="lock"></Icon>}
					type="password"
					callback={(e) => callbackObj.password(e.target.value)}
					onBlur={(e: React.FocusEvent<HTMLInputElement>) => {
						blurObj.password(e.target.value);
					}}
					placeholder="密码"
				></Input>
				<div className="bigbear-form-validate">
					{validate.password.map((v: string, i: number) => (
						<div key={i}>{v}</div>
					))}
				</div>

				<div className="login-form-submit">
					<Button
						btnType="info"
						onClick={() => {
							handleSubmit(onSubmit);
						}}
					>
						提交
					</Button>
					<Button
						btnType="success"
						onClick={() => {
							dispatch(push("/register"));
						}}
					>
						马上注册
					</Button>
				</div>
			</Form>
		</>
	);
}

const mapStateToProps = (state: CustomCombinedState): ProfileState => state.profile;

export default connect(mapStateToProps)(Register);
